<template>
    <div id="admin-manage" class="page-wrapper">
      <div class="selector-wrapper main-card wrapper">
        <div class="main-card">
          <el-form class="form" :inline="true" ref="form" :model="formData">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input v-model.trim="formData.goodsName" placeholder="请输入"></el-input>
            </el-form-item>
  
            <el-form-item label="商品等级" prop="grade">
              <el-select v-model="formData.grade" placeholder="请选择">
                <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
  
            <el-form-item label="商品分类" prop="grade">
              <el-select v-model="formData.grade" placeholder="请选择">
                <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <el-button type="primary" @click="handleSubmitClick" :loading="loading">获取数据</el-button>
        <el-button type="success" @click="addGoods">新增产品</el-button>
      </div>
      <div class="wrapper main-card">
        <el-table :data="pageData" style="width: 100%" :stripe="true">
          <el-table-column prop="goodsName" label="商品名称"></el-table-column>
          <el-table-column prop="details" label="商品详情"></el-table-column>
          <el-table-column prop="money" label="商品价格"></el-table-column>
          <el-table-column label="图片">
            <template slot-scope="scope">
              <img :src="scope.row.image" alt="图片" class="image-preview" />
            </template>
          </el-table-column>
          <el-table-column prop="inventory" label="商品库存"></el-table-column>
          <el-table-column prop="sales" label="商品销量"></el-table-column>
          <el-table-column label="商品等级">
            <template slot-scope="scope">
              <span>{{ gradeLabel(scope.row.grade) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <span>{{ scope.row.state === 1 ? '销售中' : '已下架' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <el-button @click="handleAction(scope.row, 'toggle')" :type="scope.row.state === 1 ? 'danger' : 'success'">
                {{ scope.row.state === 1 ? '下架' : '上架' }}
              </el-button>
              <el-button @click="handleAction(scope.row, 'modify')" type="primary">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>
  
      <el-dialog title="商品详情" :visible.sync="dialogVisible" width="800px" @close="resetForm">
        <el-tabs type="border-card">
          <el-form class="form" ref="form" :model="modifydata" :rules="rules">
            <div class="form-item-wrapper">
              <el-form-item label="商品名称" required prop="goodsName">
                <el-input v-model.trim="modifydata.goodsName"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" required prop="money">
                <el-input v-model.trim="modifydata.money" placeholder="请输入"></el-input>
              </el-form-item>
              <el-form-item label="商品介绍" required prop="details">
                <el-input v-model.trim="modifydata.details" placeholder="请输入"></el-input>
              </el-form-item>
            </div>
            <div class="form-item-wrapper">
              <el-form-item label="商品等级" required prop="grade">
                <el-select v-model="modifydata.grade" placeholder="请选择">
                  <el-option v-for="item in options2" :key="item.value" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="商品图片" prop="signatureImage">
                <input type="file" @change="handleFileChange" />
                <img v-if="modifydata.signatureImageUrl" :src="modifydata.signatureImageUrl" class="image-preview" />
              </el-form-item>
              <el-form-item label="商品状态" required prop="state">
                <el-select v-model="modifydata.state" placeholder="请选择">
                  <el-option label="销售中" :value="1"></el-option>
                  <el-option label="已下架" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-form>
        </el-tabs>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="uploadGoods">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { searchgoodsinfo, uploadgoodsinfo, changegoodsstate, chanhegoodsinfo } from '@/api/pcclinet';
  
  export default {
    name: 'RoomInfo',
    data() {
      return {
        currentPage: 1,
        pageData: [],
        total: 0,
        pageSize: 10,
        dialogVisible: false,
        formData: {
          goodsName: '',
          grade: '',
        },
        modifydata: {
          id: '',
          goodsName: '',
          details: '',
          money: '',
          grade: '',
          state: '',
          signatureImage: '',
          signatureImageUrl: '', // 用于预览图片
        },
        tableData: [],
        loading: false,
        rules: {
          goodsName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
          money: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
          details: [{ required: true, message: '请输入商品详情', trigger: 'blur' }],
          grade: [{ required: true, message: '请选择商品等级', trigger: 'change' }],
          state: [{ required: true, message: '请选择商品状态', trigger: 'change' }],
        },
        options2: [
          { value: 1, label: '甄选品' },
          { value: 2, label: '优选品' },
          { value: 3, label: '一级品' },
        ],
      };
    },
    methods: {
      queryByPage() {
        const start = (this.currentPage - 1) * this.pageSize;
        return this.tableData.slice(start, start + this.pageSize);
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.pageData = this.queryByPage();
      },
      handleCurrentChange(val) {
        this.currentPage = val;
        this.pageData = this.queryByPage();
      },
      handleSubmitClick() {
        this.loading = true;
        this.getGoodsData(this.formData)
      },
      handleAction(row, action) {
        if (action === 'toggle') {
          this.toggleGoodsState(row);
        } else if (action === 'modify') {
          this.modifydata = { ...row }; // 填充表单数据
          this.modifydata.signatureImageUrl = row.image; // 显示已有的商品图片
          this.dialogVisible = true; // 显示弹出框
        }
      },
      addGoods() {
        this.modifydata = { // 重置表单数据
          id: '',
          goodsName: '',
          details: '',
          money: '',
          grade: '',
          state: '',
          signatureImage: '',
          signatureImageUrl: '', // 重置预览图片
        };
        this.dialogVisible = true; // 显示弹出框
  
        // 重置表单字段和值后，清除校验状态
        this.$nextTick(() => {
          this.$refs.form.clearValidate();
        });
      },
  
      resetForm() {
        this.$refs.form.resetFields();
        this.$nextTick(() => {
          this.$refs.form.clearValidate();
        });
      },
      uploadGoods() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            const formData = new FormData();
  
            // Append all other fields
            formData.append('id', this.modifydata.id);
            formData.append('goodsName', this.modifydata.goodsName);
            formData.append('details', this.modifydata.details);
            formData.append('money', this.modifydata.money);
            formData.append('grade', this.modifydata.grade);
            formData.append('state', this.modifydata.state);
  
            // Append the file only if it exists
            if (this.modifydata.signatureImage) {
              formData.append('signatureImage', this.modifydata.signatureImage);
            }
  
            if (this.modifydata.id) {
              // 修改商品
              chanhegoodsinfo(formData)
                .then(res => {
                  if (res.success) {
                    this.dialogVisible = false;
                    this.getGoodsData();
                    this.$message.success('商品修改成功');
                  } else {
                    this.$message.error('修改商品失败: ' + res.message);
                  }
                })
                .catch(error => {
                  this.$message.error('修改商品失败，请重试');
                  console.error('Error modifying goods:', error);
                });
            } else {
              // 新增商品
              uploadgoodsinfo(formData)
                .then(res => {
                  if (res.success) {
                    this.dialogVisible = false;
                    this.getGoodsData();
                    this.$message.success('商品上传成功');
                  } else {
                    this.$message.error('上传商品失败: ' + res.message);
                  }
                })
                .catch(error => {
                  this.$message.error('上传商品失败，请重试');
                  console.error('Error uploading goods:', error);
                });
            }
          } else {
            this.$message.error('请完整填写表单信息');
          }
        });
      },
      handleFileChange(event) {
        const file = event.target.files[0];
        const maxSize = 60 * 1024; // 60KB in bytes
  
        if (file) {
          if (file.size > maxSize) {
            this.$message.error('上传的文件大小不能超过60KB');
            return;
          }
          this.modifydata.signatureImage = file;
          this.modifydata.signatureImageUrl = URL.createObjectURL(file); // 图片预览
        }
      },
      getGoodsData(filters = {}) {
        searchgoodsinfo(filters)
          .then(res => {
            if (res.success) {
              this.loading = false;
              this.tableData = res.data;
              this.total = res.data.length;
              this.pageData = this.queryByPage();
            }
          })
          .catch(error => {
            console.error('Error fetching goods data:', error);
          });
      },
      toggleGoodsState(row) {
        let data = {
          id: row.id,
          state: row.state === 1 ? 0 : 1
        };
        changegoodsstate(data)
          .then(res => {
            if (res.success) {
              this.getGoodsData();
            } else {
              console.error('Error changing goods state:', res.message);
            }
          })
          .catch(error => {
            console.error('Error changing goods state:', error);
          });
      },
      gradeLabel(grade) {
        const gradeMap = {
          1: '甄选品',
          2: '优选品',
          3: '一级品',
        };
        return gradeMap[grade] || '';
      },
      resetForm() {
        this.$refs.form.resetFields();
      }
    },
    mounted() {
      this.getGoodsData();
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .wrapper {
    margin: 40px 0;
  }
  
  .selector-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .form-item-wrapper {
    display: flex;
    justify-content: space-between;
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  
  .image-preview {
    max-width: 100px;
    max-height: 50px;
    margin-top: 10px;
  }
  </style>
  